<?php
$origin = $_SERVER['HTTP_ORIGIN'] ?? '*';
header('Access-Control-Allow-Origin: '  . $origin);
header('Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS');
header("Access-Control-Allow-Headers: Content-Type, X-Requested-With");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 3600");

$method = $_SERVER['REQUEST_METHOD']??'GET';

if ($method == 'OPTIONS') {
    // 返回允许的请求方法和头部信息
    http_response_code(204);
    exit();
}

// request url
// ?host=xxxxx&uri=xxxx
// http://localhost:8089?host=https://jira&uri=
$host = $_GET['host']??'';
$uri = $_GET['uri']??'';
$url = $host . $uri;

if (empty($host)) {
    echo json_encode(array('status' => false, 'error' => 'host is empty'));
    exit;
}

# 读取配置文件
// $configFile = $_SERVER['DOCUMENT_ROOT'] . '\\config.json';
$cacertPem = 'cacert.pem';
$configFile = 'config.json';
$config = json_decode(file_get_contents($configFile), true);
$settting = $config['setting'];
$hosts = $config['hosts'];
$proxy = $settting['proxy'];

# 匹配请求的 host
$matchHost = false;
$headerToken = false;
$token = '';
$dns = '';

foreach ($hosts as $key => $item) {
    if ($item['host'] === $host) {
        $token = $item['token'];
        $headerToken = $item['type']=='header';
        $matchHost = true;
        $dns = $item['dns'] ?? '';
        break;
    }
}

if (!$matchHost) {
    echo json_encode(array('status' => false, 'error' => 'Request host not found'));
    exit;
}

if (!$headerToken && !empty($token)) {
    $url = strchr($url, '?') ? $url . '&' : $url . '?';
    $url .= 'token=' . $token;
}

// 获取当前请求中的令牌
//$token = $_SERVER['HTTP_AUTHORIZATION'] ?? '';

$headers = [
    'content-type: application/json',
];

if ($headerToken) {
    $headers[] = sprintf('authorization: Bearer %s', $token);
}

if ($method=='PSOT') {
    $headers[] = 'Content-Type: application/x-www-form-urlencoded';
    $headers[] = 'Expect:';
}

try {
    // 创建 cURL 句柄
    $ch = curl_init();

    // 设置代理
    if ($proxy['enable']) {
        curl_setopt($ch, CURLOPT_PROXY, sprintf("%s:%d", $proxy['host'], $proxy['port'])); // 代理地址
        curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); // 代理类型
    }

    // 设置 cURL 选项
    curl_setopt($ch, CURLOPT_URL, $url); // 替换为实际的 API 终点
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    if ($method !== 'GET') {
        curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents('php://input')); // 替换为要发送的 JSON 数据
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    if ($dns) {
        curl_setopt($ch, CURLOPT_RESOLVE, [sprintf('%s:%s', parse_url($url, PHP_URL_HOST), $dns)]);
    }

    // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 禁用 SSL 验证
    // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_CAINFO, 'cacert.pem');
    curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

    // 执行请求
    $response = curl_exec($ch);

    // 检查是否有错误发生
    if ($response === false) {
        $error = curl_error($ch);
        // 处理错误，可以将错误信息保存到数组中
        $responseData = array('status' => false, 'error' => $error);
    } else {
        // 解析响应数据
        // $responseData = array('status' => true, 'data' => json_decode($response, true));
        $responseData = json_decode($response, true);
        // 设置响应 http 状态
        $httpCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        header(sprintf('HTTP/1.1 %d', $httpCode));
    }

    // 关闭 cURL 句柄
    curl_close($ch);
} catch (\Exception $e) {
     $responseData = array('status' => false, 'error' => $e->getMessage(), 'data' => ['url' => $url]);
}


// 输出响应数据或错误信息
echo json_encode($responseData);